package com.interceptor;

import com.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyInterceptor implements HandlerInterceptor {
    private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //判断有无user对象
        threadLocal.set(System.currentTimeMillis());
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("user");
        if(user == null) {
            httpServletResponse.setContentType("text/html;charset=utf-8");
            httpServletResponse.getWriter().append("用户未登录，请登录后操作");
            return false;
        }
        return true;

    }

    //在请求处理方法执行之后执行
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(httpServletRequest, httpServletResponse, o, modelAndView);
    }

    //在dispatcherServlet处理后执行,做清理工作.
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        HttpSession session=httpServletRequest.getSession();
        User user= (User) session.getAttribute("user");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.print(user.getUsername()+"|"+user.getRole()+"|"+sdf.format(new Date())+"|"+httpServletRequest.getMethod().toLowerCase()+"|"+httpServletRequest.getServletPath()+"|");
        long endTime = System.currentTimeMillis();
        long time = endTime-threadLocal.get();
        System.out.println(time);
    }
}
